//商品
(function() {
	//构造函数
	var _con = function(info) {
		var self = this;
		var domain = info.domain;
		var port = info.port;
		var is_secondary_domain = !!info.is_secondary_domain;
		var bus_id = info.bus_id;
		domain = domain.toLowerCase();

		//如果不是使用二级域名，需要写相关的配置文件
		if (!is_secondary_domain) {
			//获取正确的域名
			var sub_domain = tld.getSubdomain(domain);
			if (sub_domain === "www") {
				sub_domain = "";
			}
			domain = (sub_domain ? (sub_domain + ".") : "") + tld.getDomain(domain);
			if (!domain) {
				throwCusError("域名格式错误");
			}
			_con.checkUseAble(domain, is_secondary_domain);
			/*
			 * 独立域名需要白名单绑定
			 */
			//添加到NGNIX列表
			var nginx_config_file_name = domain + "_nginx_dotnar";
			// if(fs.existsSync("/etc/nginx/sites-available/" + nginx_config_file_name)){
			// 	throwCusError("域名已经被绑定")
			// }
			var fiber = Fiber.current;
			fs.writeFile("/etc/nginx/sites-available/" + nginx_config_file_name, nginx_config_file_template.replace("__dotmain_list__", sub_domain ? domain : (domain + "," + "www." + domain)), function(err) {
				if (err) {
					console.error(err);
				}
				fiber.run();
			});
			Fiber.yield(); //挂起

			//重载Nginx配置
			child_process.exec("/etc/init.d/nginx reload", function(error, stdout, stderr) {
				if (error !== null) {
					console.error('stderr: ' + stderr);
					console.error('更新Nginx配置出错: ' + error);
				}
				console.log('stdout: ' + stdout);
				console.log("更新Nginx配置完成");
				fiber.run();
			});
			Fiber.yield(); //挂起
		} else if (!domain) {
			throwCusError("域名格式错误");
		} else { //注册二级域名
			_con.checkUseAble(domain, is_secondary_domain);
			//已经使用泛解析*，无需动态添加
			// var fiber = Fiber.current;
			// var dnspodClient = new Dnspod({
			// 	'login_email': 'gaubee@126.com',
			// 	'login_password': '88884444'
			// });
			// dnspodClient.recordCreate({
			// 	domain_id: "19996009",
			// 	sub_domain: domain,
			// 	record_type: "A",
			// 	record_line: "默认",
			// 	value: "121.40.72.93",
			// 	mx: "5"
			// }).on("recordCreate", function(err, data) {
			// 	if (err) {
			// 		throwCusError("DNS服务器出错，请稍后重试")
			// 	} else {
			// 		console.log(data);
			// 		if (data.status.code == 1) {
			// 			// result = data;
			// 		} else {
			// 			console.error(data.status.message, domain);
			// 		}
			// 	}
			// 	fiber.run();
			// });
			// Fiber.yield(); //挂起
		}
		this.bus_id = bus_id;
		this.domain = domain;
		this.is_secondary_domain = is_secondary_domain;
		this.port = parseInt(port) || _con.getPort(info.domain);

		self._id = db_id_prefix + bus_id + "|" + domain + "|" + is_secondary_domain + "|" + this.port; //Math.random().toString(36).substr(2) + (+new Date).toString(36);
		console.log("生成一个Domain Info对象：", self);
		db.insert(db_table_name, self);
	};
	//技能
	module.exports = _con;
	_con.prototype = require("./skill");
	//静态方法
	_con.get = function(Id) {
		var result = db.find_by_id(db_table_name, Id);
		return _con.getInstance(result);
	};
	_con.getInstance = function(obj) {
		if (obj) {
			obj.__proto__ = _con.prototype;
		}
		return obj;
	};
	_con.getPort = function(url_str) {
		if (url_str.indexOf("http://") === -1 || url_str.indexOf("https://") === -1) {
			url_str = "http://" + url_str;
		}
		return url.parse(url_str).port || 80;
	};
	_con.findByBusId = function(bus_id) {
		var result = db.find_list(db_table_name, {
			bus_id: bus_id
		});
		result.forEach(function(domainInfo) {
			domainInfo.__proto__ = _con.prototype;
		});
		return result;
	};
	_con.checkUseAble = function(domain, is_secondary_domain) {
		var _domainInfo = db.find_one(db_table_name, {
			domain: domain,
			is_secondary_domain: is_secondary_domain
		});

		if (_domainInfo) {
			var bus = BusCon.get(_domainInfo.bus_id);
			if (bus && bus.domainIdList && bus.domainIdList.indexOf(_domainInfo._id) !== -1) {
				throwCusError("域名已经被使用")
			} else {
				db.remove(db_table_name, _domainInfo._id);
			}
		}
	};

	var url = require("url");
	var child_process = require('child_process');
	var fs = require("fs");
	var db = require("../db/index");
	var config = require("../_include/config");
	var db_table_name = config.dbname.domain;
	var db_id_prefix = config.dbIdPrefix.domain;
	var helper = require("../_include/helper");
	var tld = require('tldjs');
	var Dnspod = require('dnspod-client');
	var Fiber = require('fibers');
	var nginx_config_file_template = fs.readFileSync(__dirname + "/../_include/nginx_dotnar").toString();
	var BuffsCon = require("../buff/_con");
	var BusCon = require("../bus/_con");
}());